﻿/********************************************
 *** title: txt文档修改, 在章节中  001章,002章 文件修改，添加为 第001章，第002章， 有修改的时候才进行重写操作。
 *** youping 
 *** 2023-09-12
 ********************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo.FolderOp
{
    public partial class NovelOperate : Form
    {
        public NovelOperate()
        {
            InitializeComponent();
        }

        private void btnSelectDoc_Click(object sender, EventArgs e)
        {
            // 选择小说文件
            OpenFileDialog myFile = new OpenFileDialog();
            myFile.Multiselect = true;
            myFile.Title = "请选择文件";
            myFile.Filter = "所有文件(*txt*)|*.txt"; //设置选择文件的类型
            if (myFile.ShowDialog() == DialogResult.OK)
            {
                this.txtFilesPath.Text = myFile.FileName;
            }

            FileStream fs = new FileStream(this.txtFilesPath.Text, FileMode.Open, FileAccess.Read);
            Encoding r = GetType(fs);

            fs.Close();
            this.txtFormatName.Text = r.BodyName;
        }

        public System.Text.Encoding GetType(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;

        }

        /// <summary> 
        /// 判断是否是不带 BOM 的 UTF8 格式 
        /// </summary> 
        /// <param name=“data“></param> 
        /// <returns></returns> 
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

        private void btnSaveChange_Click(object sender, EventArgs e)
        {
            // 更改小说具体内容

            //var tempList = System.IO.File.ReadLines(this.txtFilesPath.Text, Encoding.Default);
            //int loop = 1;
            //foreach (var temp in tempList)
            //{

            //    if (loop > 3) {
            //        break;
            //    }
            //    loop++;
            //}
            //string[] lines = System.IO.File.ReadAllLines(this.txtFilesPath.Text, Encoding.Default);
            
            // 按照文件类型打开文件
            Encoding codeVal = Encoding.Default;
            if (!string.IsNullOrWhiteSpace(this.txtFormatName.Text))
            {
                codeVal = Encoding.GetEncoding(this.txtFormatName.Text);
            }
            else
            {
                MessageBox.Show("请选择文件！");
                return;
            }
            string[] lines = System.IO.File.ReadAllLines(this.txtFilesPath.Text, codeVal);
            bool isModifyData = false;
            for (var i = 0; i < lines.Length; i++)
            {
                if (lines[i].Contains("章") && !lines[i].Contains("第"))
                {
                    //判断当前行，章前面是否存在数字，如果存在，则新增
                    try
                    {
                        Convert.ToInt32(lines[i].Substring(0, lines[i].IndexOf("章")).Replace(" ", "").Replace("章", ""));
                        lines[i] = "第" + lines[i];
                        isModifyData = true;
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            // 更新内容
            if (isModifyData)
            {
                File.WriteAllLines(this.txtFilesPath.Text, lines, Encoding.Default);
                MessageBox.Show("修改成功！");
            }
            else {
                MessageBox.Show("文件未修改！");
            }
            //foreach (string line in lines) {
            //    if (line.Contains("章") && !line.Contains("第")) {
            //        line = "第" + line;

            //        break;
            //    }
            //}
            //string temp_1 = "";
            //temp_1 = "1";
        }

        #region 更新小说重复行为空行
        /// <summary>
        /// 更新小说重复行为空行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelDoubleData_Click(object sender, EventArgs e)
        {
            // 按照文件类型打开文件
            Encoding codeVal = Encoding.Default;
            if (!string.IsNullOrWhiteSpace(this.txtFormatName.Text))
            {
                codeVal = Encoding.GetEncoding(this.txtFormatName.Text);
            }
            else
            {
                MessageBox.Show("请选择文件！");
                return;
            }
            string[] lines = System.IO.File.ReadAllLines(this.txtFilesPath.Text, codeVal);
            bool isModifyData = false;
            
            string oldContent = string.Empty;
            string tempContent = string.Empty;
            int loop = 0;
            int linesLen = lines.Length;
            for (int i = 0; i < linesLen; i++)
            {
                oldContent = lines[i].Replace(" ", "");
                if (!string.IsNullOrEmpty(oldContent))
                {
                    loop = i;
                    break;
                }
            }
            for (int i = loop + 1; i < linesLen; i++)
            {
                tempContent = lines[i].Replace(" ", "");
                if (string.IsNullOrEmpty(tempContent))
                {
                    continue;
                }
                else if (tempContent == oldContent)
                {
                    lines[i] = "";
                    isModifyData = true;
                }
                else
                {
                    oldContent = tempContent;
                }
            }
            // 更新内容
            if (isModifyData)
            {
                File.WriteAllLines(this.txtFilesPath.Text, lines, Encoding.Default);
                MessageBox.Show("修改成功！");
            }
            else
            {
                MessageBox.Show("文件未修改！");
            }
        }
        #endregion

        #region 删除相关行包含“===”内容的行全部删除
        /// <summary>
        /// 删除相关行包含“===”内容的行全部删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelRelatedLineContain_Click(object sender, EventArgs e)
        {
            // 按照文件类型打开文件
            Encoding codeVal = Encoding.Default;
            if (!string.IsNullOrWhiteSpace(this.txtFormatName.Text))
            {
                codeVal = Encoding.GetEncoding(this.txtFormatName.Text);
            }
            else
            {
                MessageBox.Show("请选择文件！");
                return;
            }
            string[] lines = System.IO.File.ReadAllLines(this.txtFilesPath.Text, codeVal);
            bool isModifyData = false;

            string relatedContent = "===";
            string tempContent = string.Empty;
            int loop = 0;
            int linesLen = lines.Length;
            for (int i = loop + 1; i < linesLen; i++)
            {
                tempContent = lines[i].Replace(" ", "");
                if (tempContent.Contains(relatedContent))
                {
                    lines[i] = "";
                    isModifyData = true;
                }
            }
            // 更新内容
            if (isModifyData)
            {
                File.WriteAllLines(this.txtFilesPath.Text, lines, Encoding.Default);
                MessageBox.Show("修改成功！");
            }
            else
            {
                MessageBox.Show("文件未修改！");
            }
        }
        #endregion
    }
}
